<template>
  <div class="createPost-container">
    <el-form
      :model="productInfo"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="产品名称" prop="storeName">
            <el-input v-model="productInfo.storeName"></el-input>
          </el-form-item>

          <el-form-item label="产品分类" prop="cateIds">
            <el-checkbox-group v-model="productInfo.cateIds">
              <el-checkbox v-for="cate in cateList" :label="cate.key" :key="cate.key">{{cate.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="产品封面" prop="image">
            <Upload v-model="productInfo.image" />
            <span class="el-upload__tip">只能上传jpg/jpeg/png文件，建议尺寸为600px*600px</span>
          </el-form-item>

          <el-form-item label="产品视频" prop="videoLink">
            <el-upload
              class="upload-video"
              :action="uploadVideoAction"
              :on-preview="handleVideoPreview"
              :on-remove="handleVideoRemove"
              :before-remove="beforeVideoRemove"
              :multiple=false
              :limit="1"
              :on-exceed="handleVideoExceed"
              :on-success="handleVidelSuccess"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <span slot="tip" class="el-upload__tip"> 只能上传MP4文件，且不超过20M</span>
            </el-upload>
          </el-form-item>

          <el-form-item label="产品轮播图" prop="sliderImage">
            <Upload4 v-model="productInfo.sliderImage" />
            <span class="el-upload__tip">只能上传jpg/jpeg/png文件，建议尺寸为600px*600px</span>
          </el-form-item>

          <!-- <el-form-item label="会员价格" prop="vipPrice">
            <el-input v-model.number="productInfo.vipPrice"></el-input>
          </el-form-item> -->
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="售价" prop="price">
                  <el-input v-model.number="productInfo.price"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="市场价" prop="marketPrice">
                  <el-input v-model.number="productInfo.marketPrice"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <!-- 库存 -->
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="库存" prop="stock">
                  <el-input v-model.number="productInfo.stock"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="单位" prop="unitName">
                  <el-input v-model="productInfo.unitName"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <!-- 排序 -->
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="排序" prop="sort">
                  <el-input v-model.number="productInfo.sort"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="内容详细" name="second">
          <el-form-item label="产品描述" prop="storeInfo">
            <Tinymce ref="editor" v-model="productInfo.storeInfo" :height="400" />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">立即保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateProduct, getProductInfo } from "@/api/prodecuManger";
import { productCateList } from "@/api/product-cate";
import Upload from "@/components/Upload/SingleImage";
import Upload4 from "@/components/Upload/SingleImage4";
import Tinymce from '@/components/Tinymce'

export default {
  data() {
    return {
      loading: false,
      uploadVideoAction: process.env.VUE_APP_UPLOAD_BASE_URL + 'api/v1/file/upload',
      uploadSliderAction: process.env.VUE_APP_UPLOAD_BASE_URL + 'api/v1/file/upload',
      activeName: 'first',
      cateList: [],
      fileList: [],
      sliderImages: [],
      dialogVisible: true,
      productInfo: {
        id: 0,
        activity: "",
        barCode: "",
        cateIds: [],
        cost: 0,
        ficti: 0,
        givePoint: 0,
        image: "",
        isPostage: 0,
        is_benefit: 0,
        is_best: 0,
        is_good: 0,
        is_hot: 0,
        is_new: 0,
        is_seckill: 0,
        is_show: 0,
        is_vip: 0,
        keyword: "",
        marketPrice: 0,
        postage: 0,
        price: 0,
        recommendImage: "",
        sales: 0,
        sliderImage: "",
        sort: 100,
        specType: 0, 
        stock: 0,
        storeInfo: "",
        storeName: "",
        tempId: 0,
        unitName: "",
        videoLink: "",
        vipPrice: 0   // 会员价格
      },
      rules: {
        storeName: [{required: true, message: "请输入商品名称", trigger: "blur"}],
        cateIds:[{required: true, message: "请选择商品分类", trigger: "blur"}],
        price: [{required: true,  type: "number", message: "请输入价格，只能输入数字", trigger: "blur"}],
        stock: [{required: true, type: "number", message: "请输入库存", trigger: "blur"}],
        image: [{required: true, message: "请上传产品图", trigger: "change"}],
        unitName: [{required: true, message: "请填写单位", trigger: "change"}],
        storeInfo: [{required: true, message: "请填写产品描述", trigger: "blur"}]
      }
    };
  },
  components: {
    Upload,
    Tinymce,
    Upload4
  },
  created() {
    // 需要编辑的产品ID
    let id = this.$route.params && this.$route.params.id;
    // 获取产品详细
    getProductInfo({id: id}).then(response => {
      if (response.success == true)
      {
        this.productInfo.id = response.data.id;
        this.productInfo.storeName = response.data.storeName;
        this.productInfo.image = response.data.image;
        this.productInfo.price = response.data.price;
        this.productInfo.marketPrice = response.data.marketPrice;
        this.productInfo.unitName = response.data.unitName;
        this.productInfo.stock = response.data.stock;
        this.productInfo.sort = response.data.sort;
        this.productInfo.storeInfo = response.data.storeInfo;
        this.productInfo.is_show = response.data.is_show;
        this.productInfo.sliderImage = response.data.sliderImage;

        let categoryList = response.data.productCateglories
        for (var i in categoryList)
        {
          this.productInfo.cateIds.push(categoryList[i].id);
        }

        this.productInfo.videoLink = response.data.videoLink;

        // 处理文件名称
        if (response.data.videoLink)
        {
          let videoNames = (response.data.videoLink).split('/');
          (this.fileList).push({name: videoNames[videoNames.length - 1], url: response.data.videoLink});
        }
      }
    });
    this.getCateList()
  },
  methods: {
    getCateList() {
      // 商品分类
      productCateList({pageType: 'A'}).then(response => {
          let data = response.data;
          for (let i in data) {
            this.cateList.push({ key: data[i].id, name: data[i].cateName });
          }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.loading = true;
          try {
            const { success, errorDetail } = await updateProduct(this.productInfo);
            if (success == true) {
              this.$notify({
                title: "成功",
                message: "产品编辑成功",
                type: "success",
                duration: 2000
              });
              this.$router.go(-1);
            }
            else
            {
              this.$notify({
                title: "失败",
                message: errorDetail != null ? errorDetail : "产品编辑失败",
                type: "error",
                duration: 2000
              });
            }
          } finally {
            this.loading = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 视频
    handleVideoRemove(file, fileList) {
      this.productInfo.videoLink = '';
      console.log('video', file, fileList);
    },
    handleVideoPreview(file) {
      console.log('video', file);
      window.open(file.url);
    },
    handleVideoExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleVidelSuccess (response, file, fileList){
      if (response.success == true)
      {
        this.productInfo.videoLink = response.data.path;
      }
    },
    beforeVideoRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 轮播
    handleSliderSuccess(res, file) {
      if (res.success === true)
      {
          this.sliderImages.push(res.data.path);
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeSliderUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;
  margin-top: 20px;
  padding: 10px;
  box-sizing: border-box;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
